<template>
  <el-form-item :label="addText">
    <el-button @click="addItem" type="primary">{{ props.addText }}</el-button>
  </el-form-item>
  <template v-for="(domain, index) in props.modelValue" :key="domain.key">
    <el-form-item
      :label="props.paramKey + (index + 1)"
      :prop="props.paramName + '.' + index + '.paramKey'"
      :rules="{
        required: true,
        message: `${props.paramKey + (index + 1)}必填！`,
        trigger: 'blur'
      }"
    >
      <el-input :model-value="domain.paramKey" @input="changeItem($event, 'paramKey', index)" />
    </el-form-item>
    <el-form-item
      :label="props.paramValue + (index + 1)"
      :prop="props.paramName + '.' + index + '.paramValue'"
      :rules="{
        required: true,
        message: `${props.paramValue + (index + 1)}必填！`,
        trigger: 'blur'
      }"
    >
      <el-input :model-value="domain.paramValue" @input="changeItem($event, 'paramValue', index)" />
    </el-form-item>
    <el-form-item
      :label="props.paramKey + '(英文)' + (index + 1)"
      :prop="props.paramName + '.' + index + '.paramKey_en'"
    >
      <el-input :model-value="domain.paramKey_en" @input="changeItem($event, 'paramKey_en', index)" />
    </el-form-item>
    <el-form-item
      :label="props.paramValue + '(英文)' + (index + 1)"
      :prop="props.paramName + '.' + index + '.paramValue_en'"
    >
      <el-input :model-value="domain.paramValue_en" @input="changeItem($event, 'paramValue_en', index)" />
    </el-form-item>
    <el-form-item>
      <el-button class="mt-2" @click.prevent="removeItem(index)">删除</el-button>
    </el-form-item>
  </template>
</template>

<script lang="ts" setup>
import { cloneDeep } from "lodash-es"
import { PropType } from "vue"

const props = defineProps({
  addText: {
    type: String,
    default: "添加参数"
  },
  paramKey: {
    type: String,
    default: "参数名称"
  },
  paramValue: {
    type: String,
    default: "参数值"
  },
  paramName: String,
  modelValue: {
    type: Array as PropType<any[]>,
    default: () => []
  }
})

const emit = defineEmits(["update:modelValue"])
const removeItem = (index: number) => {
  if (index !== -1) {
    emit(
      "update:modelValue",
      props.modelValue.filter((item, idx) => idx !== index)
    )
  }
}

const addItem = () => {
  const list = cloneDeep(props.modelValue)
  list.push({
    key: Date.now(),
    paramKey: "",
    paramValue: "",
    paramKey_en: "",
    paramValue_en: ""
  })
  emit("update:modelValue", list)
}
const changeItem = (value: string, key: string, index: number) => {
  console.log(value, key, index)

  const list = cloneDeep(props.modelValue)
  list[index][key] = value
  console.log(list)

  emit("update:modelValue", list)
}
</script>
